const {
    logger,
    sleep,
    saveScreenshot,
    checkCaptcha,
    SendSms,
} = require('./util');

const step1 = async page => {
    await page.evaluate(() => {
        document.querySelector('.addressType').click();
    });
    //等待按钮变红
    for (let i=0; i<5; i++) {
        const check = await page.$('.ti-button-disabled');
        if (check) {
            await sleep(2000);
        }
    }
    //内容已填好，直接下一步
    logger('下一步1');
    await page.click('#paid-shipping-address-select');
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/multi/cn-tax-invoice', { waitUntil: 'domcontentloaded' });
    //有时有可能会跳过发票确认，直接进入第3步的“规定”
    logger('等待页面跳转...');
    await page.waitForSelector('#cmpCheckboxflag', {
        timeout: 60000
    });
    await sleep(10000);
}

const step2 = async page => {
    logger('进入了发票确认页');
    await sleep(5000);
    //增值税发票确认
    logger('增值税发票确认');
    await page.click('#cmpCheckboxflag');
    await sleep(1000);
    //下一步
    logger('下一步2');
    await page.click('#tax-invoice-submit');
    await sleep(1000);
    //弹出弹框要求确认发票
    logger('确认发票并继续');
    await page.$$eval('.vat-modal-button', e => e[1].click());
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/regulations-step/choose', { waitUntil: 'domcontentloaded' });
    logger('等待页面跳转...');
    await page.waitForSelector('#regulations-select', {
        timeout: 60000
    });
    await sleep(10000);
}

const step3 = async page => {
    //规定 选择[游戏] 和 [游戏控制器和外设]
    logger('选择“游戏”和“游戏控制器和外设”，是否军方采购');
    await sleep(5000);
    await page.evaluate(async () => {
        $('#waiver_accept').click();
        $('#regulations-select').val('游戏').change();
        await new Promise(resolve => setTimeout(resolve, 2000));
        $('#checkout-regulations-select').val('游戏控制器和外设').change();
        await new Promise(resolve => setTimeout(resolve, 2000));
        $('.militoryRadio').eq(1).click();
        await new Promise(resolve => setTimeout(resolve, 2000));
        $('.militoryRadio').eq(1).click();
    });
    logger('等待按钮可点');
    //等待按钮变红
    for (let i=0; i<5; i++) {
        const check = await page.$('.ti-button-disabled');
        if (check) {
            await sleep(3000);
        }
    }
    //下一步
    logger('下一步3');
    await page.$eval('#regulations-submit-btn', e => e.click());
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/delivery-method/choose', { waitUntil: 'domcontentloaded' });
    logger('等待页面跳转...');
    await page.waitForSelector('.js-checkout-toc-radio', {
        timeout: 60000
    });
    await sleep(10000);
}

const step5 = async page => {
    //接受/拒绝
    //这里貌似需要滚一下里面的条款，才能点。所以直接用它自带的jQuery来修改
    logger('接受/拒绝');
    await sleep(5000);
    await page.evaluate(async () => {
        $('.js-checkout-toc-radio').prop("disabled", false);
        $('.toc-lbl-disabled').each(function() {
            $(this).removeClass('toc-lbl-disabled');
        });
        await new Promise(resolve => setTimeout(resolve, 1000));
        $('#terms_accept').click();
        await new Promise(resolve => setTimeout(resolve, 1000));
        $('#terms_accept').click();
        await new Promise(resolve => setTimeout(resolve, 1000));
    });
    //下一步
    logger('下一步4');
    await page.$eval('#shipping-method-submit', e => e.click());
    logger('等待页面跳转...');
    //await page.goto('https://www.ti.com.cn/store/ti/zh/checkout/buy/multi/payment-method/add', { waitUntil: 'domcontentloaded' });
    await page.waitForSelector('#payment-method-unionpay_b', {
        timeout: 60000
    });
    await sleep(10000);
}

const step6 = async page => {
    //支付方式，选择“企业支付”
    logger('选择支付方式');
    await sleep(5000);
    await page.$eval('#payment-method-unionpay_b', e => e.click());
    await page.waitForSelector('#warning-unionpay_b .js-apm-paymentbtn', {
        timeout: 60000
    });
    await sleep(2000);
    //确认
    logger('确认支付');
    await page.$eval('#warning-unionpay_b .js-apm-paymentbtn', e => e.click());
    logger('等待下单结果...');
    await page.waitForSelector('#citconPaymentDiv .modal-body iframe', {
        timeout: 60000
    });
    await sleep(10000);
}

//下单操作
exports.goAndPay = async page => {
    let curStep = 0;
    try {
        logger('准备下单');

        await page.waitForSelector('#paid-shipping-address-select', {
            timeout: 60000
        });
        await sleep(10000);

        curStep = 1;
        try {await step1(page);} catch (e) {await step1(page);}
        curStep = 2;
        try {await step2(page);} catch (e) {await step2(page);}
        curStep = 3;
        try {await step3(page);} catch (e) {await step3(page);}
        curStep = 5;
        try {await step5(page);} catch (e) {await step5(page);}
        curStep = 6;
        try {await step6(page);} catch (e) {await step6(page);}

        logger('下单成功!', page.url());
        await saveScreenshot(page, 'succ');
    } catch(e) {
        logger('下单出错', page.url(), e);
        await saveScreenshot(page, 'order');
        await checkCaptcha(page);
        SendSms({
            TemplateId: '1169784',
            TemplateParamSet:[
                '支付', '第'+curStep+'步'
            ]
        }, 'dev');
        return false;
    }

    logger('获取订单号');
    let orderNo = '';
    try {
        //获取订单号
        const iframe = await page.$('#citconPaymentDiv .modal-body iframe');
        const iframeUrl = await page.evaluate(dom => dom.getAttribute('src'), iframe);
        await page.goto(iframeUrl);
        logger(`打开订单页 ${iframeUrl}`);
        await page.waitForSelector('span.reference', {
            timeout: 60000
        });
        await sleep(10000);
        orderNo = await page.evaluate(() => {
            return document.querySelector('span.reference') && document.querySelector('span.reference').innerText;
        });
    } catch(e) {
        logger('获取订单号出错', page.url(), e);
        await saveScreenshot(page, 'get_order');
        await checkCaptcha(page);
    }

    logger('本次订单号为'+orderNo);
    //发送短信
    SendSms({
		TemplateId: '1169785',
		TemplateParamSet:[orderNo]
	});

    return true;
}
